import { useStore } from 'vuex' 

let data
let webSocketInstance
const planetSocket = ()=>{
    //const wsUrl = 'ws://localhost:30021/boboPlanetUserMiddleDev/boboPlanet/websocket'
    const wsUrl = 'ws://localhost:30008/gateway/out/boboPlanetUserMiddleDev/boboPlanet/websocket'
    let ws = new WebSocket(wsUrl)
    let store = useStore()
    webSocketInstance = ws
    //连接成功
    ws.onopen = function(event){
        console.log("连接到websocket成功")

        // getWsData()
    }
    //接收到后台发送的数据
    ws.onmessage = function(event){
        let wsArr = []
        wsArr.push(JSON.parse(event.data))
        store.commit('setWebSocketMsg',wsArr)
        //ws.close()
    }
    //关闭
    ws.onclose = function(event){
        console.log("websocket连接关闭")
    }
}

// 接收到后台发送的数据
const getWsData = ()=>{
    webSocketInstance.onmessage = function(event){
        console.log("收到websocket消息:",event.data)
        return event.data
        //ws.close()
    }
}

//关闭websocket
function wsClose(){
    if(webSocketInstance){
        webSocketInstance.close()
        webSocketInstance = null
    }
}


export{
    planetSocket,
    getWsData,
    wsClose
}
